package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.model.mongo.UserLocation;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class UserLocationApiImpl implements UserLocationApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    //上报地理位置
    @Override
    public void save(Long userId, Double latitude, Double longitude, String addrStr) {
        //1. 查询当前用户是否存在当前位置
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = Query.query(criteria);
        boolean exists = mongoTemplate.exists(query, UserLocation.class);

        //2. 判断是否存在
        if (!exists){
            //2.1 不存在时，创建
            UserLocation userLocation = new UserLocation();
            userLocation.setUserId(userId);
            userLocation.setLocation(new GeoJsonPoint(longitude,latitude));
            userLocation.setAddress(addrStr);
            userLocation.setCreated(System.currentTimeMillis());
            mongoTemplate.save(userLocation);
        }else {
            //2.2 存在时，更新
            Update update = new Update();
            update.set("location",new GeoJsonPoint(longitude,latitude));
            update.set("updated",System.currentTimeMillis());
            update.set("address",addrStr);
            mongoTemplate.updateFirst(query,update,UserLocation.class);
        }

    }

    //获取附近人的id
    @Override
    public List<Long> searchNear(Long userId, String distance) {
        //1. 查询原点(坐标点)
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = Query.query(criteria);
        UserLocation location = mongoTemplate.findOne(query, UserLocation.class);
        GeoJsonPoint point = location.getLocation();
        //2. 创建半径
        Double r = Double.valueOf(distance);
        Distance dis = new Distance(r / 1000, Metrics.KILOMETERS);
        //3. 创建圆形
        Circle circle = new Circle(point, dis);
        //4. 根据圆形获取地理位置
        Criteria criteria1 = Criteria.where("location").withinSphere(circle);
        Query query1 = Query.query(criteria1);
        List<UserLocation> userLocations = mongoTemplate.find(query1, UserLocation.class);
        //5. 返回(利用工具类，将集合中的id返回到集合中)
        return CollUtil.getFieldValues(userLocations,"userId",Long.class);
    }
}
